<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * Version :  v1.0.0
 * Date    :  2023/5/30 14:05
 */

namespace App\Controller;

use Hyperf\Codec\Json;
use Hyperf\Context\Context;
use Hyperf\Contract\ConfigInterface;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface as HttpResponseInterface;
class BaseController extends AbstractController
{
    /**
     * @var HTTP CODE 配置
     */
    protected $HttpCode;

    /**
     * @var $config 配置对象
     */
    protected $config;


    public function __construct()
    {
        $this->config = $this->container->get(ConfigInterface::class);
        // 设置HTTP状态码配置
        $this->HttpCode = $this->config->get('http_code');
    }

    /**
     * 获取登录用户信息
     * date 2023/5/30 11:36
     * @return array|mixed|user_info 用户信息
     */
    public function getUserAsToken()
    {
        $user = Context::get('user_info');
        if(is_null($user)){
            return ['id'=>0,'name'=>'未知姓名','nickname'=>'未知昵称'];
        }
        return $user;
    }

    /**
     * 成功响应
     * date 2023/5/30 12:10
     */
    public function success($code, $msg, $data = null)
    {
        return $this->response->json(["code" => $code, "message" => $msg, "data" => $data]);
    }

    /**
     * 异常响应
     * date 2023/5/30 15:39
     * @param int $http_code http状态码
     * @param int $code 业务状态码
     * @param string $message 错误消息
     * @return HttpResponseInterface 响应对象
     */
    public function fail(string $message = '', int $http_code = 400, int $code = 1)
    {
        return make(HttpResponseInterface::class)->withHeader('Server', \Hyperf\Support\env("APP_NAME"))
            ->withStatus($http_code)->withBody(new SwooleStream(Json::encode(["code"=>$code,"message"=>$message])));
    }
}